package com.greenline.search.report;

import com.greenline.search.report.entity.LogReportResult;
import com.greenline.search.report.entity.SearchWord;
import com.greenline.search.report.model.Configuration;
import com.greenline.search.report.model.GenerateReportResult;
import com.greenline.search.report.util.*;
import com.greenline.search.test.utils.JSONStreamParserForAnalyze;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: liulei
 * Date: 14-2-12
 * Time: 下午2:39
 * To change this template use File | Settings | File Templates.
 */
public class GetTopQuery {
    private static Logger logger = LoggerFactory.getLogger(GetTopQuery.class);
    //一个月列表（不要被名字所迷惑）
    private List<String> oneMonthLogNameList;
    //一个月搜索列表（不要被名字所迷惑）
    private List<SearchWord> oneMonthSearchWordList;

    public GetTopQuery(){
        Date today = new Date();
        oneMonthLogNameList = Arrays.asList(
                DateUtils.getLastWeekLogNameArray(today,30));
        oneMonthSearchWordList = new LinkedList<SearchWord>();
        initSearchWordList(oneMonthLogNameList,oneMonthSearchWordList);
    }
    //把每个文件里的词都聚合到searchWordList
    public void initSearchWordList(List<String> logNameList, List<SearchWord> searchWordList){
        for(String fileName : logNameList){
            logger.info("Read file " + fileName + ".txt in process...");
            String filePath = Configuration.ROOT_PATH+fileName.substring(0,6)+
                    Configuration.FOLDER_BACKSLASH+fileName+".txt";
            List<String> fileContents = FileUtils.readFileAsString(filePath,"UTF-8");
            for(String content : fileContents){
                SearchWord searchWord;
                String[] contentSplit = content.split("\"\t\"");
                try {
                    if(contentSplit[0].length() > 1){
                        String word = contentSplit[0].substring(1,contentSplit[0].length()).trim();
                        if(word.contains("xE") || word.trim().length() <= 0){
                            continue;
                        }
                        searchWord = JSONStreamParserForAnalyze.getWordType(word);
                        searchWord.setText(word);
                        searchWord.setFrequency(Integer.parseInt(contentSplit[1]));
                        if(searchWordList.contains(searchWord)){
                            int wordIndex = searchWordList.indexOf(searchWord);
                            SearchWord originalSearchWord = searchWordList.get(wordIndex);
                            searchWord.setFrequency(searchWord.getFrequency()+originalSearchWord.getFrequency());
                            searchWordList.set(wordIndex,searchWord);
                        } else {
                            searchWordList.add(searchWord);
                        }
                    }else {
                        continue;
                    }
                }catch (StringIndexOutOfBoundsException e){
                    e.printStackTrace();
                }
            }
        }
        System.out.println("The search word size is " + searchWordList.size());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        logger.info("Get top query...");
        GetTopQuery topQuery = new GetTopQuery();
        List<SearchWord> wordList = topQuery.getOneMonthSearchWordList();
        Collections.sort(wordList);
//        int count = 20000;
//        count = count < wordList.size() ? count : wordList.size();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < wordList.size(); i++){
            if(wordList.get(i).getFrequency() < 30){
                break;
            }
            sb.append(wordList.get(i).getText()).append("\t")
                    .append(wordList.get(i).getFrequency()).append("\n");
        }
        logger.info(sb.toString());
        logger.info("Total cost time {} seconds.", (System.currentTimeMillis()-startTime)/1000);
    }

    public List<String> getOneMonthLogNameList() {
        return oneMonthLogNameList;
    }

    public void setOneMonthLogNameList(List<String> oneMonthLogNameList) {
        this.oneMonthLogNameList = oneMonthLogNameList;
    }

    public List<SearchWord> getOneMonthSearchWordList() {
        return oneMonthSearchWordList;
    }

    public void setOneMonthSearchWordList(List<SearchWord> oneMonthSearchWordList) {
        this.oneMonthSearchWordList = oneMonthSearchWordList;
    }
}